<?php 

class HotelRoomAndDates extends CActiveRecord
{
	public function tableName()
	{
		return lfirst(__CLASS__);
	}
	
	public static function model($className = __CLASS__)
    {
    	return parent::model(lfirst(__CLASS__));
    }
    
    static function getConfig()
    {
    	$config = new CConfiguration('protected/config/pricesGrid.php');
		$config = $config->toArray();
		
		return $config['grid'];
    }
    
    public function getPricesWithDates($hotelId, $orderString = null)
    {
    	$sql = "select * from hotelRoomAndDates as hrad
    			    inner join hotelRoom as hr on hrad.hotelRoomId = hr.id
    			    inner join hotelDateGroup as hdg on hrad.hotelDateGroupId = hdg.id
  				  where hr.hotelId = " . intval($hotelId) . "
    			    and hdg.hotelId = " . intval($hotelId);
    	
    	if ($orderString) {
    		$sql .= ' order by ' . $orderString; 
    	}
    	
    	$command = Yii::app()->db->createCommand($sql);
    	
		return $command->queryAll();
    }
    
    static function updateData($data, $hotelId)
    {
    	$columns = HotelDateGroup::model()->findAll('hotelId=:hotelId', array(':hotelId' => $hotelId));
    	
    	if (isset($data->title)) {
    		HotelRoom::model()->updateByPk(intval($data->id), array('title' => $data->title), 'hotelId=:hotelId', array(':hotelId' => $hotelId));
    	}
    	
    	foreach ($columns as $col) {
    		$key = 'dateField' . $col->id;
    		if (isset($data->$key)) {
    			$rows = HotelRoomAndDates::model()->updateAll(
    				array('price' => $data->$key),
    				'hotelRoomId=:hotelRoomId and hotelDateGroupId=:hotelDateGroupId',
    				array(
    					':hotelRoomId' => $data->id,
    					':hotelDateGroupId' => $col->id
    				)
    			);
    			
    			if ($rows == 0) {
    				$hotelRoomAndDates = new HotelRoomAndDates();
					$hotelRoomAndDates->hotelRoomId = $data->id;
					$hotelRoomAndDates->hotelDateGroupId = $col->id;
					$hotelRoomAndDates->price = $data->$key;
					$hotelRoomAndDates->save();
    			}
    		}
    	}
    }
}